package com.biblioteca.model.tableModels;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

import com.biblioteca.model.entities.Obra;
import com.biblioteca.view.FramePrincipal;


@SuppressWarnings("serial")
public class ObraTableModel extends AbstractTableModel {

	private FramePrincipal fp;
	private Statement st ;
	private ResultSet rs ;	
	
	
	public ArrayList<Obra> obras = new ArrayList<Obra>();
	private String nomes[] = {"ID", "T�tulo", "Autor", "Categoria", "Qtd Total", "Qtd Emprestada"} ;
	public ArrayList<Obra> obrasAux = obras ;
	
	public ObraTableModel(FramePrincipal fp) {
		this.fp = fp ;
		try {
			st = fp.conn.createStatement() ;
			rs = st.executeQuery("SELECT * FROM OBRA ORDER BY id");	
			while (rs.next()) {
				obras.add( new Obra (rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6)) ) ;
			}
			st.close();
		} catch(Exception e) {
			e.printStackTrace() ;
		}
	}
	
	@Override
	public int getColumnCount() {
		return 6 ;
	}

	@Override
	public int getRowCount() {
		return obras.size() ;
	}

	@Override
	public Object getValueAt(int row, int column) {
		Obra o = obras.get(row);
		switch (column) {
		case 0:
			return o.getId();
		case 1:
			return o.getTitulo();
		case 2:
			return o.getAutor();
		case 3:
			return o.getCategoria();
		case 4:
			return o.getQtdTotal();
		case 5:
			return o.getQtdEmp();
		}
		return null;
	}

	public void linhaAdicionada() {
		try {
			st = fp.conn.createStatement() ;
			rs = st.executeQuery("SELECT * FROM Obra WHERE id=(SELECT MAX(id) FROM Obra)") ;
			if (rs.next()) obras.add( new Obra (rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6)) ) ;
			fireTableRowsInserted(obras.size()-1,obras.size()-1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public String getColumnName(int column){
		return nomes[column] ;
	}

}
